summaryrefslogtreecommitdiff
path: root/app/api/swp/download/[fileId]/route.ts
blob: fe422015fddda3947b42851ce892eaf38471af0a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
import { NextRequest, NextResponse } from "next/server";
import { downloadDocumentFile } from "@/lib/swp/document-service";
import { debugLog, debugError, debugSuccess } from "@/lib/debug-utils";

// API Route 설정
export const runtime = "nodejs";
export const maxDuration = 60; // 1분 타임아웃

/**
 * GET /api/swp/download/[ownDocNo]?projNo=xxx&fileName=xxx
 * 파일 다운로드 (Full API 기반)
 * 
 * Query Parameters:
 * - projNo: 프로젝트 번호
 * - fileName: 파일명
 */
export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ fileId: string }> }
) {
  try {
    const { fileId: ownDocNo } = await params;
    const { searchParams } = new URL(request.url);
    const projNo = searchParams.get("projNo");
    const fileName = searchParams.get("fileName");

    debugLog(`[download] 다운로드 시작`, { projNo, ownDocNo, fileName });

    // 파라미터 검증
    if (!projNo || !ownDocNo || !fileName) {
      debugError(`[download] 필수 파라미터 누락`, { projNo, ownDocNo, fileName });
      return NextResponse.json(
        { 
          success: false, 
          error: "필수 파라미터가 누락되었습니다. (projNo, ownDocNo, fileName)" 
        },
        { status: 400 }
      );
    }

    // document-service의 downloadDocumentFile 사용
    const result = await downloadDocumentFile(projNo, ownDocNo, fileName);

    if (!result.success || !result.data) {
      debugError(`[download] 다운로드 실패`, { error: result.error });
      return NextResponse.json(
        { 
          success: false, 
          error: result.error || "파일 다운로드 실패" 
        },
        { status: 404 }
      );
    }

    debugSuccess(`[download] 다운로드 성공`, {
      fileName: result.fileName,
      size: result.data.length,
      mimeType: result.mimeType,
    });

    // Uint8Array를 Buffer로 변환
    const buffer = Buffer.from(result.data);

    // 바이너리 응답 반환
    return new NextResponse(buffer, {
      status: 200,
      headers: {
        "Content-Type": result.mimeType || "application/octet-stream",
        "Content-Disposition": `attachment; filename="${encodeURIComponent(result.fileName || fileName)}"`,
        "Content-Length": String(buffer.length),
      },
    });
  } catch (error) {
    console.error("[download] 오류:", error);
    debugError(`[download] 다운로드 실패`, {
      error: error instanceof Error ? error.message : String(error),
      stack: error instanceof Error ? error.stack : undefined
    });
    
    return NextResponse.json(
      {
        success: false,
        error: error instanceof Error ? error.message : "파일 다운로드 실패",
      },
      { status: 500 }
    );
  }
}